Range Sum Query - Immutable || Range Sum Query 2D - Immutable

Range Sum Query - Immutable

Question

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

1
2
3
4
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:
You may assume that the array does not change.
There are many calls to sumRange function.

Analysis
  • 假如每次调用sumRange的时候相加会导致TLE,所以采用动态规划
  • sum数组为当前脚标到脚标0的所有数字的加和,则SumRange=sum[j]-sum[i-1],注意是i-1,因为需要包含脚标i的值
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class NumArray {
private int[] sum;
public NumArray(int[] nums) {
int size=nums.length;
sum=new int[size];
int tmp=0;
for(int i=0;i<size;i++){
tmp+=nums[i];
sum[i]=tmp;
}
}
public int sumRange(int i, int j) {
return i==0?sum[j]:sum[j]-sum[i-1];
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

Range Sum Query 2D - Immutable

Question

Given a 2D matrix matrix, picfind the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

1
2
3
4
5
6
7
8
9
10
11
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.

Analysis
  • 二维数组dp记录当前坐标与坐标(0,0)所包含的全部的数字加和
  • cal数组需要考虑到第一行与第一列的情况,从而进行计算
  • 在计算sumRegion的时候需要注意最后的求和中,需要对脚标进行-1操作,不可直接通过计算面积的方式考量得出公式。
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class NumMatrix {
int[][] dp;
public NumMatrix(int[][] matrix) {
int rowsize=matrix.length;
int colsize=0;
if(rowsize!=0)
colsize=matrix[0].length;
dp=new int[rowsize][colsize];
for(int i=0;i<rowsize;i++){
for(int j=0;j<colsize;j++){
cal(matrix,i,j);
}
}
}
public void cal(int[][] matrix, int i, int j){
if(i==0&&j==0)
dp[i][j]=matrix[i][j];
else if(i==0&&j!=0)
dp[i][j]=dp[i][j-1]+matrix[i][j];
else if(i!=0&&j==0)
dp[i][j]=dp[i-1][j]+matrix[i][j];
else
dp[i][j]=dp[i-1][j]+dp[i][j-1]+matrix[i][j]-dp[i-1][j-1];
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int right_top = row1 > 0 ? dp[row1-1][col2] : 0;
int left_bottom = col1 > 0 ? dp[row2][col1 - 1]:0;
int left_top = row1 > 0 && col1 > 0 ? dp[row1 - 1][col1 - 1] : 0;
return dp[row2][col2] - right_top - left_bottom + left_top;
}
}
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);